<template>
  <div class='user'>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="formList.query" clearable @clear='getData'>
            <el-button slot="append" icon="el-icon-search" @click='getData'></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-search" @click='dialogVisible = true'>添加用户</el-button>
        </el-col>
      </el-row>
        <el-table
          :data=tableData
          stripe
          style="width: 100%">
          <el-table-column type='index'></el-table-column>
          <el-table-column
            prop="username"
            label="姓名">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话">
          </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色">
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change='statuChange(scope.row)'></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width='180px'>
            <template slot-scope='scope'>
              <el-button type="primary" size='mini' icon="el-icon-edit" @click='changeUser(scope.row)'></el-button>
              <el-button type="danger" size='mini' icon="el-icon-delete" @click='deleteUser(scope.row.id)'></el-button>
              <el-tooltip content="分配角色" placement="top" :enterable='false' >
                <el-button type="warning" size='mini' icon="el-icon-setting" @click='settingUser(scope.row)'></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <el-form ref="ref_addForm" :model='addForm' :rules='addFormRules' label-width='70px'>
        <el-form-item label="用户名" prop='username'>
          <el-input v-model='addForm.username'></el-input>
        </el-form-item>
        <el-form-item label="密码" prop='password'>
          <el-input type='password' v-model='addForm.password'></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop='email'>
          <el-input v-model='addForm.email'></el-input>
        </el-form-item>
        <el-form-item label="手机" prop='mobile'>
          <el-input v-model='addForm.mobile'></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改用户" :visible.sync="changeUserVisi" width="50%" @close='editClose'>
      <el-form ref="ref_editForm" :model="editForm" :rules='editFormRules' label-width="70px">
        <el-form-item label="用户名" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop='email'>
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop='mobile'>
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeUserVisi = false">取 消</el-button>
        <el-button type="primary" @click='editSubmit'>确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog @close='settingUserDialogClose' title="分配角色" :visible.sync="settingUserVisi" width="50%" >
      <div>
        <p>当前的用户：{{ userData.username }}</p>
        <p>当前的角色：{{ userData.role_name }}</p>
        <p>分配角色
          <el-select v-model="selectroleid" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingUserVisi = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

<script>
export default {
  data(){
    var validateEmail = (rule, value, callback) => {
      if( value == '' ) callback()
      const zz = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if ( zz.test(value) ) callback()
      else callback(new Error('请输入合法的邮箱'))
    }
    var validateMobile = (rule, value, callback) => {
      if( value == '' ) callback()
      const zz = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if ( zz.test(value) ) return callback()
      else return callback(new Error('请输入合法的手机号'))
    }
    return {
      tableData:[],
      dialogVisible:false,
      changeUserVisi:false,
      settingUserVisi:false,
      rolesList:[],
      userData:'',
      selectroleid:'',
      total:0,
      formList:{
        query:'',
        pagenum:1,
        pagesize:2,
      },
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      addFormRules:{
        username:[
          { required:true, message:'请输入用户名', trigger:'blur'},
          { min:3, max:10, message:'用户名的长度在3-10个字符', trigger:'blur'}
        ],
        password:[
          { required:true, message:'请输入密码', trigger:'blur'},
          { min:6, max:15, message:'用户名的长度在6-15个字符', trigger:'blur'}
        ],
        email:[
          { required:false, message:'请输入邮箱', trigger:'blur'},
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile:[
          { required:false, message:'请输入手机', trigger:'blur'},
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      editForm:{},
      editFormRules:{
        email:[
          { required:false, message:'请输入邮箱', trigger:'blur'},
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile:[
          { required:false, message:'请输入手机', trigger:'blur'},
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
    }
  },
  methods:{
    async getData(){
      let data = await this.axios.get('/users', {
        params: this.formList
      })
      if(data.data.meta.status != 200){
        this.pop.error('获取列表失败！！')
        return 
      }
      this.total = data.data.data.total
      this.tableData = data.data.data.users
    },
    handleSizeChange(index){
      this.formList.pagesize = index
      this.getData()
    },
    handleCurrentChange(index){
      this.formList.pagenum = index
      this.getData()
    },
    async statuChange(data){
      let res = await this.axios.put(`users/${ data.id }/state/${ data.mg_state }`)
      if(res.data.meta.status == 200) this.pop.success(res.data.meta.msg)
      else {
        this.pop.error(res.data.meta.msg)
        data.mg_state = !data.mg_state
      }
    },
    addUsers(){
      this.$refs.ref_addForm.validate( async result=>{
        if( !result ) return
        let res = await this.axios.post('/users', this.addForm)
        if( res.data.meta.status == 201) {
          this.pop.success(res.data.meta.msg)
          this.dialogVisible = false
        } else {
          this.pop.error(res.data.meta.msg)
        }
      })
    },
    async changeUser(data){
      
      let res = await this.axios.get(`/users/${ data.id }`)
      if(res.data.meta.status == 200) {
        this.editForm = res.data.data
        this.changeUserVisi = true
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    editClose(){
      this.$refs.ref_editForm.resetFields()
    },
    editSubmit(){
      this.$refs.ref_editForm.validate( async result=>{
        if( !result ) return
        let res = await this.axios.put(`users/${ this.editForm.id }`, this.editForm)
        if(res.data.meta.status == 200) {
          this.pop.success(res.data.meta.msg)
          this.getData()
          this.changeUserVisi = false
        } else {
          this.pop.error(res.data.meta.msg)
        }
      })
    },
    async deleteUser(id){
      let res = await this.confirm('此操作将永久删除用户数据！！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch( err => err)
      if( res == 'confirm' ) {
        let data = await this.axios.delete('/users/' + id)
        if( data.data.meta.status == 200 ) {
          this.pop.success( data.data.meta.msg )
          this.getData()
        } else this.pop.error( data.data.meta.msg )
      }
    },
    async settingUser(row){
      this.userData = row
      let res = await this.axios.get('/roles')
      if( res.data.meta.status == 200 ) {
        this.rolesList = res.data.data
      } else {
        this.pop.error(res.data.meta.msg)
      }
      this.settingUserVisi = true
    },
    async saveRole(){

      if( !this.selectroleid) {
        return this.pop.error('请选择一个角色。。')
      }
      let res = await this.axios.put(`users/${ this.userData.id }/role`, {
        rid: this.selectroleid
      })
      if( res.data.meta.status == 200 ){
        this.pop.success(res.data.meta.msg)
        this.getData()
        this.settingUserVisi = false
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    settingUserDialogClose() {
      this.selectroleid = ''
      this.userData = ''
    }
  },
  mounted(){
    this.getData()
  },
}
</script>

<style lang='scss' scoped>

.user .el-breadcrumb {
  padding:15px 0 ;
}



</style>